package com.example.demo.service;

import com.example.demo.dao.mapper.SysSessionMapper;
import com.example.demo.dao.model.SysSession;
import com.example.demo.dao.model.SysSessionCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("jimmy_sessionService")
@Transactional(transactionManager = "transactionManager", timeout = 500,
        isolation = Isolation.READ_COMMITTED, rollbackFor = {Exception.class, Throwable.class, RuntimeException.class})
public class SessionService implements ISessionService {

    @Autowired
    private SysSessionMapper sysSessionMapper;

    @Autowired
    private ITokenService tokenService;

    @Override
    public SysSession selectOne(String sessionId) {
        return sysSessionMapper.selectByPrimaryKey(sessionId);
    }

    @Override
    public List<SysSession> selectMany(SysSession criteria) {

        SysSessionCriteria sysCriteria = new SysSessionCriteria();
        sysCriteria.createCriteria().andDelFlagEqualTo(0);
        return this.sysSessionMapper.selectByCriteria(sysCriteria);
    }

    @Override
    public Boolean insertSession(SysSession session) {
        String sessionId = UUID.randomUUID().toString();
        session.setSessionId(sessionId);
        session.setCreateBy("admin");
        session.setUpdateBy("admin");
        long now = System.currentTimeMillis();
        session.setCreateTime(new Date(now));
        session.setUpdateTime(new Date(now));
        session.setUserId("0");
        session.setExpireTime(new Date(now + (12 * 3600 * 1000)));
        int count = this.sysSessionMapper.insertSelective(session);

        // do insert token
        /*SysToken token = new SysToken();
        token.setBlackFlag(0);
        token.setDelFlag(0);
        token.setSessionId(sessionId);
        token.setToken(TokenUtil.createToken());
        this.tokenService.insertToken(token);*/

        return count > 0;
    }

    @Override
    public Boolean updateSession(SysSession session) {

        session.setUpdateBy("admin");
        long now = System.currentTimeMillis();
        session.setUpdateTime(new Date(now));
        int count = this.sysSessionMapper.updateByPrimaryKeySelective(session);
        return count > 0;
    }
}
